import { useQuery } from "@tanstack/react-query";
import { useWebSocket } from "@/hooks/use-websocket";
import { useEffect, useState } from "react";
import { 
  CheckCircle, 
  BarChart3, 
  Clock, 
  AlertTriangle,
  RefreshCw,
  Download,
  Fan
} from "lucide-react";
import { StatusCard } from "@/components/status-card";
import { ProxyRulesTable } from "@/components/proxy-rules-table";
import { QuickConfigForm } from "@/components/quick-config-form";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { ScrollArea } from "@/components/ui/scroll-area";
import { apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";

export default function Dashboard() {
  const { toast } = useToast();
  const { lastMessage } = useWebSocket();
  const [currentTime, setCurrentTime] = useState(new Date());
  const [recentLogs, setRecentLogs] = useState<any[]>([]);

  const { data: metrics } = useQuery({
    queryKey: ["/api/system-metrics"],
    refetchInterval: 5000,
  });

  const { data: logs = [] } = useQuery({
    queryKey: ["/api/proxy-logs"],
    select: (data) => data.slice(0, 10),
  });

  const { data: proxyRules = [] } = useQuery({
    queryKey: ["/api/proxy-rules"],
  });

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  useEffect(() => {
    if (lastMessage) {
      if (lastMessage.type === 'NEW_LOG') {
        setRecentLogs(prev => [lastMessage.data, ...prev.slice(0, 9)]);
      }
    }
  }, [lastMessage]);

  useEffect(() => {
    setRecentLogs(logs);
  }, [logs]);

  const activeProxies = proxyRules.filter((rule: any) => rule.status === 'running').length;

  const handleRestartService = async () => {
    try {
      await apiRequest("POST", "/api/system/restart");
      toast({ title: "服务重启成功" });
    } catch (error) {
      toast({ title: "重启失败", variant: "destructive" });
    }
  };

  const handleExportConfig = async () => {
    try {
      const response = await fetch("/api/system/export-config");
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = 'frp-config.json';
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      toast({ title: "配置导出成功" });
    } catch (error) {
      toast({ title: "导出失败", variant: "destructive" });
    }
  };

  const handleClearLogs = async () => {
    try {
      await apiRequest("DELETE", "/api/proxy-logs");
      toast({ title: "日志清理成功" });
    } catch (error) {
      toast({ title: "清理失败", variant: "destructive" });
    }
  };

  const getLogLevelBadge = (level: string) => {
    const colors = {
      INFO: "bg-green-100 text-green-800",
      DEBUG: "bg-blue-100 text-blue-800", 
      WARN: "bg-yellow-100 text-yellow-800",
      ERROR: "bg-red-100 text-red-800",
    };
    
    return (
      <Badge className={colors[level as keyof typeof colors] || "bg-gray-100 text-gray-800"}>
        {level}
      </Badge>
    );
  };

  return (
    <div className="flex-1 overflow-hidden">
      {/* Header */}
      <header className="bg-white border-b border-slate-200 px-6 py-4">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-semibold text-slate-800">仪表板</h2>
            <p className="text-slate-600">代理服务器状态监控</p>
          </div>
          <div className="flex items-center space-x-4">
            <Button className="bg-primary hover:bg-blue-700">
              新建代理
            </Button>
            <div className="flex items-center space-x-2 text-slate-600">
              <Clock className="w-4 h-4" />
              <span className="text-sm">
                {currentTime.toLocaleTimeString('zh-CN', { hour12: false })}
              </span>
            </div>
          </div>
        </div>
      </header>

      {/* Dashboard Content */}
      <div className="p-6 overflow-y-auto h-full">
        {/* Status Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <StatusCard
            title="活跃代理"
            value={activeProxies}
            icon={CheckCircle}
            iconColor="bg-green-100 text-green-600"
            trend={{
              value: "2",
              isPositive: true,
              label: "较昨天"
            }}
          />
          <StatusCard
            title="今日流量"
            value={metrics?.totalTraffic || "0GB"}
            icon={BarChart3}
            iconColor="bg-blue-100 text-blue-600"
            trend={{
              value: "15%",
              isPositive: true,
              label: "较昨天"
            }}
          />
          <StatusCard
            title="平均响应时间"
            value={`${metrics?.avgResponseTime || 0}ms`}
            icon={Clock}
            iconColor="bg-yellow-100 text-yellow-600"
            trend={{
              value: "8ms",
              isPositive: false,
              label: "较昨天"
            }}
          />
          <StatusCard
            title="错误率"
            value={metrics?.errorRate || "0%"}
            icon={AlertTriangle}
            iconColor="bg-red-100 text-red-600"
            trend={{
              value: "0.03%",
              isPositive: false,
              label: "较昨天"
            }}
          />
        </div>

        {/* Main Dashboard Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Proxy Rules Panel */}
          <div className="lg:col-span-2">
            <ProxyRulesTable />
          </div>

          {/* System Status Panel */}
          <div className="space-y-6">
            {/* Server Status */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg font-semibold text-slate-800">服务器状态</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-slate-600">CPU使用率</span>
                    <span className="text-slate-800 font-medium">{metrics?.cpuUsage || 0}%</span>
                  </div>
                  <Progress value={metrics?.cpuUsage || 0} className="h-2" />
                </div>
                
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-slate-600">内存使用率</span>
                    <span className="text-slate-800 font-medium">{metrics?.memoryUsage || 0}%</span>
                  </div>
                  <Progress value={metrics?.memoryUsage || 0} className="h-2" />
                </div>
                
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-slate-600">网络I/O</span>
                    <span className="text-slate-800 font-medium">{metrics?.networkIO || "0 MB/s"}</span>
                  </div>
                  <Progress value={45} className="h-2" />
                </div>
              </CardContent>
            </Card>

            {/* Recent Logs */}
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="text-lg font-semibold text-slate-800">实时日志</CardTitle>
                  <Button variant="ghost" size="sm">
                    <RefreshCw className="w-4 h-4" />
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                <ScrollArea className="h-64">
                  <div className="space-y-3">
                    {recentLogs.length === 0 ? (
                      <div className="text-center text-slate-500 py-8">
                        暂无日志记录
                      </div>
                    ) : (
                      recentLogs.map((log, index) => (
                        <div key={index} className="flex items-start space-x-3 text-sm">
                          <span className="text-slate-400 text-xs mt-1">
                            {new Date(log.timestamp).toLocaleTimeString('zh-CN')}
                          </span>
                          <div className="flex-1">
                            {getLogLevelBadge(log.level)}
                            <span className="text-slate-600 ml-2">{log.message}</span>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                </ScrollArea>
              </CardContent>
            </Card>

            {/* Quick Actions */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg font-semibold text-slate-800">快速操作</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <Button 
                  className="w-full bg-primary hover:bg-blue-700" 
                  onClick={handleRestartService}
                >
                  <RefreshCw className="w-4 h-4 mr-2" />
                  重启服务
                </Button>
                <Button 
                  variant="outline" 
                  className="w-full"
                  onClick={handleExportConfig}
                >
                  <Download className="w-4 h-4 mr-2" />
                  导出配置
                </Button>
                <Button 
                  variant="outline" 
                  className="w-full"
                  onClick={handleClearLogs}
                >
                  <Fan className="w-4 h-4 mr-2" />
                  清理日志
                </Button>
              </CardContent>
            </Card>
          </div>
        </div>

        {/* Quick Configuration Panel */}
        <div className="mt-8">
          <QuickConfigForm />
        </div>
      </div>
    </div>
  );
}
